<?php
class Users extends MY_Controller{

	function __construct(){
		parent::__construct();

			if(!$this->checkUserStatus()){
			redirect('login');
		}else{
			$this->aauth->update_activity();
			if(!$this->control(1)){
				redirect('noAccess');
			}

		}

	}


	function index(){

		$data['toDoList'] = $this->get_tasks();
		$data['title'] = $this->title('Utilisateurs');
		$data['user'] = $this->aauth->get_user();
		$data['userList'] = $this->aauth->list_users(FALSE,FALSE,FALSE,TRUE);
		$this->load->view($this->theme.'/header',$data);
		$this->load->view($this->theme.'/users/index');
		$this->load->view($this->theme.'/footer');

	}

	function addUser(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('name','nom & prénom', 'required');
		$this->form_validation->set_rules('email','email', 'required|valid_email|is_unique[aauth_users.email]');
		$this->form_validation->set_rules('password','mot de passe','required|min_length[8]|max_length[13]|matches[passconf]');
		$this->form_validation->set_rules('passconf','confirmation', 'required');
		$this->form_validation->set_error_delimiters('<p class="text-red">', '</p>');
		$this->form_validation->set_message('rule', 'Error Message');
		$this->form_validation->set_message('is_unique', "L'%s est déjà existe");
		if($_POST){

			if($this->form_validation->run() == false){

			}else{
				
				$newUser = $this->aauth->create_user($_POST['email'],$_POST['password'],$_POST['passconf'],$_POST['name']);
				if($newUser){
					if($this->aauth->get_group_name($_POST['group']) != 'Default'){
						$this->aauth->remove_member($newUser,'Default');
						$this->aauth->add_member($newUser,$_POST['group']);
						redirect('users');
					}
					redirect('users');
				}else{
					$data['errors'] = $this->aauth->get_errors_array();

				}
			}
		}

		$data['toDoList'] = $this->get_tasks();
		$data['title'] = $this->title('Utilisateurs');
		$data['user'] = $this->aauth->get_user();
		$this->load->view($this->theme.'/header',$data);
		$this->load->view($this->theme.'/users/addUser');
		$this->load->view($this->theme.'/footer');

	}


	function modification(){

		if(!$_POST){
			redirect("error_404");
		}else{

			$pk = $_POST['pk'];
			$name = $_POST['name'];
			$value = $_POST['value'];
			if(!empty($value) ) {
				if($name == 'email'){
					if($this->checkValidEamil($value)){
						$this->aauth->update_user($pk,$value,false,false);
						//header('HTTP 200 OK', true, 200);
						echo $name;
					}else{
						//header('HTTP 400 Bad Request', true, 400);
						echo "Le format d'email n'est pas correct!";
					}
				}elseif($name == 'name'){
					$this->aauth->update_user($pk,false,false,$value);
					//header('HTTP 200 OK', true, 200);
					echo $name;
				}elseif($name == 'telephone'){
					$item = aauth_user::find_by_id($pk);
					$item->$name = $value;
					$item->save();
					echo $name;
				}elseif($name == 'address'){
					$item = aauth_user::find_by_id($pk);
					$item->$name = $value;
					$item->save();
					echo $name;
				}else{
					if( $this->aauth->get_user_id() == $pk){
						//header('HTTP 400 Bad Request', true, 400);
						echo "vous ne pouvez pas modifier par votre même";
					}else{
						$this->aauth->remove_member($pk,$name);
						$this->aauth->add_member($pk,$value);
						//header('HTTP 200 OK', true, 200);
						echo $name;
					}
				}
					
			} else {

				//header('HTTP 400 Bad Request', true, 400);
				echo "Ce champ est obligatoire!";
			}

		}

	}


	function reset_login_attempt()
	{
		if($_POST){
			$this->aauth->reset_login_attempts($_POST['user_id']);
			redirect('users');
		}else{
			redirect('');
		}
	}



	function selectData($item = null)
	{
		if($item == null)
		redirect('error_404');

		$data = $this->get_selectData($item);

		if($data){
			echo json_encode($data);
		}else{
			//header('HTTP 400 Bad Request', true, 400);
			echo "Interne Errors !";
		}

	}



	function bannedUser()
	{
		if(!$_POST){
			redirect('error_404');
		}else{
			$id = $_POST['id'];
			$this->aauth->ban_user($id);
			if($this->aauth->is_banned($id)){
				echo json_encode(TRUE);
			}else{
				echo json_encode(FALSE);
			}

		}
	}

	function unbanUser()
	{
		if(!$_POST){
			redirect('error_404');
		}else{
			$id = $_POST['id'];
			$this->aauth->unban_user($id);
			if(!$this->aauth->is_banned($id)){
				echo json_encode(TRUE);
			}else{
				echo json_encode(FALSE);
			}

		}
	}


	function deleteUser()
	{
		if(!$_POST){
			redirect('error_404');
		}else{
			$id = $_POST['id'];
			if(!$this->checkAgent($id)){
				if($this->do_deleteUser($id)){
					echo json_encode(TRUE);
				}else{
					echo json_encode(FALSE);
				}
			}else{
					
				$properties_id = property::find('all',array('select'=>'id','conditions'=>array('aauth_user_id'=>$id)));
					
				if($properties_id ){
					foreach ($properties_id as $p){
						$update = property::find_by_id($p->id);
						$update->aauth_user_id = '';
						$update->save();
					}
				}
				$deleteItem = agent::find($id);
				$deleteItem->delete();

				if($this->do_deleteUser($id)){
					echo json_encode(TRUE);
				}else{
					echo json_encode(FALSE);
				}
			}
		}
	}

	function sendVerifyCode(){
		
		if(!$_POST){
			redirect('error_404');
		}else{
		$user_id = $_POST['id'];
		
		$user = aauth_user::find_by_id($user_id);
		$email = $user->email;
		if($this->aauth->remind_password($email)){
			echo json_encode(true);
		}else{
			echo json_encode(false);
		}
		
		}
		
	}
	
	
	private function get_selectData($item)
	{
		$d = array();

		switch ($item):

		case 'group':
			$data = $this->aauth->list_groups();
			foreach ($data as $i){
				if($i->name != 'Public' AND $i->name != 'Default'){
					$d[] = array('value'=>$i->id,'text'=>$i->name);
				}
			}
			break;


			endswitch;

			return $d;
	}


	private function checkValidEamil($email)
	{
		return filter_var($email, FILTER_VALIDATE_EMAIL);

	}


	private function do_deleteUser($id){

		$user = aauth_user::find_by_id($id);
		if($user->avatar){
			$file_to_delete = $user->avatar;
			$path_file = 'uploads/avatar/thumbs/'.$file_to_delete;
			unlink($path_file);
		}
		$this->aauth->delete_user($id);
		return true;
	}


	private function checkAgent($id)
	{

		$item = agent::find_by_aauth_user_id($id);
		if($item){
			return true;
		}else{
			return false;
		}
	}



}